const obj = {
    a: 1,
    b: [1, 2, {c: true}, [3]],
    d: {
        e: 3,
        f: 4
    },
    g: null
}
// 输出
// {
//     a: 1,
//     'b[0]': 1,
//     'b[1]': 2,
//     'b[2].c': true,
//     'b[3][0]': 3,
//     'd.e': 3,
//     'd.f': 4
//   }
const flattenRes = flattenObj(obj)

console.log(flattenRes)


function flattenObj(obj) {
    let res = {}
    const help = (target, oldKey) => {
        for (let key in target) {
            let newKey
            if (oldKey) {
                if (Array.isArray(target)) {
                    newKey = `${oldKey}[${key}]`
                } else {
                    newKey = `${oldKey}.${key}`
                }
            } else {
                if (Array.isArray(target)) {
                    newKey = `[${key}]`
                } else {
                    newKey = key
                }
            }
            
            if (Object.prototype.toString.call(target[key]) === '[object Object]' || Array.isArray(target[key])) {
                help(target[key], newKey)
            } else if (target[key] !== null && typeof target[key] !== 'undefined') {
                res[newKey] = target[key]
            }
        }
    }
    help(obj, '')

    return res
}